<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Go To Page</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      nav {
        overflow: hidden;
      }
      nav ul {
        position: fixed;
        display: flex;
        justify-content: space-around;
        width: 100%;
        height: 80px;
        background-color: #2b2b2b;
        list-style-type: none;
        cursor: pointer;
      }
      nav ul li {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 80px;
        color: #fff;
      }
      nav ul li:hover {
        background-color: #d19a66;
      }
      article {
        overflow: hidden;
      }
      article section {
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-weight: bold;
        width: 100vw;
        height: 100vh;
      }
      article section:nth-child(1) {
        background-color: #45aaf2;
      }
      article section:nth-child(2) {
        background-color: #4b7bec;
      }
      article section:nth-child(3) {
        background-color: #a55eea;
      }
      article section:nth-child(4) {
        background-color: #0fb9b1;
      }
      input[type='button'] {
        position: fixed;
        right: 20px;
        bottom: 50px;
      }
    </style>
  </head>
  <body>
    <nav>
      <ul>
        <li class="box1">首页</li>
        <li class="box2">关于</li>
        <li class="box3">服务</li>
        <li class="box4">联系</li>
      </ul>
    </nav>
    <article>
      <section id="box1">首页</section>
      <section id="box2">关于</section>
      <section id="box3">服务</section>
      <section id="box4">联系</section>
    </article>
    <!-- 这里！因为已经封装好了calculate函数，直接传对应的参数即可 -->
    <input type="button" value="按钮" onclick="calculate('body', 30);" />
  </body>
  <script>
    // 1.绑定点击事件
    let liList = document.querySelectorAll('nav ul li');
    for (let i = 0; i < liList.length; i++) {
      liList[i].addEventListener('click', function () {
        calculate(`#${this.className}`);
      });
    }
    // 2.计算高度，进行移动
    // @param {String} value , dom节点
    // @param {Number} speed , 每10毫秒移动的像素距离
    function calculate(value, speed = 10) {
      let nowHeight = window.pageYOffset; // 当前高度
      let newHeight = document.querySelector(value).offsetTop; // 需要移动的高度
      let poor = Math.abs(newHeight - nowHeight); // 计算两个高度差，并取正
      let add = newHeight > nowHeight ? true : false; // 判断需要移动的高度是在当前高度的前面还是后面，设置布尔值
      let setIntervalId = setInterval(function () {
        if (poor <= 0) {
          // 当高度差没有的时候清除定时器
          clearInterval(setIntervalId);
        }
        poor -= speed; // 根据速度，减去相对应的高度
        window.scrollBy(0, add ? speed : -speed); // 根据之前设置布尔值进行加减。
      }, 10);
    }
  </script>
</html>
